import { Config, Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { BizCustomerListEntity } from '../entity/list';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import axios from 'axios';
import * as crypto from 'crypto';

/**
 * 微信服务
 */
@Provide()
export class BizWxService extends BaseService {
  @Config('module.bizCustomer')
  config;

  @Inject()
  ctx;

  @InjectEntityModel(BizCustomerListEntity)
  bizCustomerListEntity: Repository<BizCustomerListEntity>;

  /**
   * 获得小程序session
   * @param code 微信code
   * @param conf 配置
   */
  async miniSession(code: any) {
    const { appid, secret } = this.config.wx.mini;
    const result = await axios.get(
      'https://api.weixin.qq.com/sns/jscode2session',
      {
        params: {
          appid,
          secret,
          js_code: code,
          grant_type: 'authorization_code',
        },
      }
    );

    return result.data;
  }

  /**
   * 小程序信息解密
   * @param encryptedData
   * @param iv
   * @param sessionKey
   */
  async miniDecryptData(encryptedData, iv, sessionKey) {
    sessionKey = Buffer.from(sessionKey, 'base64');
    encryptedData = Buffer.from(encryptedData, 'base64');
    iv = Buffer.from(iv, 'base64');
    try {
      // 解密
      const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv);
      // 设置自动 padding 为 true，删除填充补位
      decipher.setAutoPadding(true);
      // @ts-ignore
      let decoded = decipher.update(encryptedData, 'binary', 'utf8');
      // @ts-ignore
      decoded += decipher.final('utf8');
      // @ts-ignore
      decoded = JSON.parse(decoded);
      return decoded;
    } catch (err) {
      throw new CoolCommException('获得信息失败');
    }
  }
}
